package com.ruoyi.stream.framework.core;


import com.ruoyi.stream.framework.config.IOTaskGroupConfig;
import com.ruoyi.stream.framework.core.workDomain.SingleIOTaskGroup;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class DefaultSingleIOTaskGroupFactory {

    private final Queue<SingleIOTaskGroup> groups = new ConcurrentLinkedQueue<>();

    private Iterator<SingleIOTaskGroup> groupQueueIterator ;

    @Autowired
    private IOTaskGroupConfig config;

    @PostConstruct
    private void init(){
        for (Integer i = 0; i < config.ioTaskNumber; i++) {
            SingleIOTaskGroup singleIOTaskGroup = new SingleIOTaskGroup();
            singleIOTaskGroup.start();
            groups.add(singleIOTaskGroup);
        }
        groupQueueIterator = groups.iterator();
    }

    public synchronized SingleIOTaskGroup getGroup(){
        if (config.ioTaskNumber<=1){
            return groups.peek();
        }else {
            if (!groupQueueIterator.hasNext()) {
                groupQueueIterator = groups.iterator();
            }
            return groupQueueIterator.next();
        }
    }
}
